package com.zuozhj.service.impl;

import com.zuozhj.common.dto.SysMenuDTO;
import com.zuozhj.entity.SysMenu;
import com.zuozhj.entity.SysUser;
import com.zuozhj.mapper.SysMenuMapper;
import com.zuozhj.mapper.SysUserMapper;
import com.zuozhj.service.ISysMenuService;
import com.zuozhj.service.ISysUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zuozhj
 * @since 2022-12-02
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {

    @Autowired
    SysUserMapper sysUserMapper;

    // 其他地方引用过sysuserservice ,这里循环引用需要在配置文件设置spring.main.allow-circular-references=true
    @Autowired
    ISysUserService sysUserService;

    @Override
    public List<SysMenuDTO> getCurrentUserNav() {
        
        String username = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        SysUser sysUser = sysUserService.getByUsername(username);
       
        List<Long> menuIds = sysUserMapper.getNavMenuIds(sysUser.getId());
        
        List<SysMenu> menus = this.listByIds(menuIds);

        // 根据menu表中的parentid转换成树状结构
        List<SysMenu> menuTree = buildTreeMenu(menus);
    
        return convert(menuTree);
    }

    private List<SysMenuDTO> convert(List<SysMenu> menuTree) {

        List<SysMenuDTO> menuDto = new ArrayList<>();

        menuTree.forEach(menu -> {
            SysMenuDTO dto = new SysMenuDTO();
                dto.setId(menu.getId());
                dto.setName(menu.getPerms());
                dto.setTitle(menu.getName());
                dto.setIcon(menu.getIcon());
                dto.setPath(menu.getPath());
                dto.setComponent(menu.getComponent());
                if (menu.getChildren().size() > 0) {
                    dto.setChildren(convert(menu.getChildren()));
                }
            menuDto.add(dto);
        });

        return menuDto;
    }

    private List<SysMenu> buildTreeMenu(List<SysMenu> menus) {

        List<SysMenu> finalMenus = new ArrayList<>();

        for (SysMenu menu : menus) {
            for (SysMenu m : menus) {
                if (menu.getId() == m.getParentId()) {
                    menu.getChildren().add(m);
                }
            }

            if (menu.getParentId() == 0) {
                finalMenus.add(menu);
            }
        }

        return finalMenus;
    }

    @Override
    public List<SysMenu> tree() {
        
        List<SysMenu> tree = this.list(new QueryWrapper<SysMenu>().orderByAsc("orderNum"));

        return buildTreeMenu(tree);
    }

}
